package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.google.gson.Gson;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.ZlineApplication;
import com.zline.foodraise.adapter.AddrListAdapter;
import com.zline.foodraise.baidu.LocationUtil;
import com.zline.foodraise.baidu.PoiSearchUtil;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.db.DatabaseHelper;
import com.zline.foodraise.db.dao.CityDao;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.City;
import com.zline.foodraise.entity.JsAddrBean;
import com.zline.foodraise.entity.UserAddressBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.EmojiFilter;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.DrawableDividerItemDecoration;
import com.zline.foodraise.view.materialedittext.MaterialEditText;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.SystemService;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by heshantao on 15/7/4.
 * 地址设置
 */
@EActivity(R.layout.activity_set_addr)
public class SetAddrActivity extends ZlineActivity implements BDLocationListener
        , OnGetPoiSearchResultListener, RecyclerItemClicked {
    private static final String LOG_TAG = SetAddrActivity.class.getSimpleName();
    //标题
    @StringRes(R.string.set_addr)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.add_addr_iv)
    ImageView current_location_iv;
    //定位当前的城市
    @ViewById(R.id.addr_city_tv)
    TextView city_tv;
    //POI 搜索结果提示
    @ViewById(R.id.addr_list_hint)
    TextView history_addr_or_searchResult_tv;
    @ViewById(R.id.add_addr_tv)
    TextView current_location_tv;
    @ViewById(R.id.addr_set_mtv)
    MaterialEditText materialEditText;
    @StringRes(R.string.current_location_addr)
    String current_location;
    @ViewById(R.id.addr_list_recyclerView)
    RecyclerView addr_recyclerView;
    SparseArray<UserAddressBean> addrArray, poiArray;
    @Bean
    AddrListAdapter adapter;
    @Bean
    LocationUtil locationUtil;
    @Bean
    PoiSearchUtil poiSearchUtil;
    @SystemService
    InputMethodManager inputMethodManager;
    @App
    ZlineApplication zlineApplication;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    LinearLayoutManager layoutManager;
    DatabaseHelper helper;
    CityDao cityDao;
    List<City> list;
    @Pref
    AppPref_ appPref;
    @StringRes(R.string.searching)
    String searching;
    //当前面定位失败时候是否需要重新定位
    boolean needLocation = false;


    @AfterInject
    void doSomeAfterInject() {
        initData();
        initLocation();
        initPoi();
    }

    @AfterViews
    void doSomeAfterViews() {
        initView();
        setRecyclerView();
        String token = appPref.token().get();
        //当没有登录不调用历史地址接口
        if (!StringUtils.isBlank(token)) {
            history_addr_or_searchResult_tv.setText(R.string.history_addr_hint);
            requestAddrList();
        }
    }

    //初始化定位
    void initLocation() {
        locationUtil.setDBLocationListener(SetAddrActivity.this);
        locationUtil.initLocationClient();
    }


    //初始化Poi
    void initPoi() {
        SDKInitializer.initialize(zlineApplication);
        poiSearchUtil.setPoiSearchListener(SetAddrActivity.this);
    }


    void initView() {
        title_tv.setText(title);
        current_location_tv.setText(current_location);
        LUtil.i(LOG_TAG, "_________城市名_____" + appPref.city().get());
        setLocationCity(appPref.city().get());
        current_location_iv.setImageResource(R.mipmap.location);
        materialEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {//监听搜索软键盘
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    poiSearchUtil.requestPoi(EmojiFilter.filterEmoji(city_tv.getText().toString().trim()),
                            EmojiFilter.filterEmoji(materialEditText.getText().toString().trim()),
                            Constant.POI_CAPACITY);
                    inputMethodManager.hideSoftInputFromWindow(materialEditText.getWindowToken(), 0);
                    showLoadingDialog();
                    return true;
                }
                return false;
            }
        });

    }


    void setRecyclerView() {
        addr_recyclerView.addItemDecoration(new DrawableDividerItemDecoration(getResources().getDrawable(R.drawable.recycleview_divider), true, true));
        addr_recyclerView.setHasFixedSize(true);
        addr_recyclerView.setItemAnimator(new DefaultItemAnimator());
        addr_recyclerView.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        addr_recyclerView.setLayoutManager(layoutManager);
        adapter.setAdapterData(addrArray);
        adapter.setRecycleItemClickListener(this);
        addr_recyclerView.setAdapter(adapter);
    }

    void initData() {
        addrArray = new SparseArray<UserAddressBean>();
    }


    //请求收货地址列表
    void requestAddrList() {
        httpOperator.requestUserAddrList(httpUtil, requestAddrListHandler);
    }


    //获取收货地址回调
    AsyncHttpResponseHandler requestAddrListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAddrListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        addrArray = httpDataParsing.getUserAddrList(response);
                        loadMoreData(addrArray);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            LUtil.i(LOG_TAG, "____failure__________" + responseString.toString());
        }
    };


    @OnActivityResult(Constant.ADDR_SET_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data, @OnActivityResult.Extra String value) {
        switch (resultCode) {
            case Constant.PROVINCE_CHOOSE_RESULT_CODE:
                setLocationCity(value);
                LUtil.i(LOG_TAG, "________选择城市__________" + value);
                break;
            default:
                break;
        }
    }


    //加载更多数据
    void loadMoreData(SparseArray<UserAddressBean> userAddressBeanSparseArray) {
        adapter.addAll(userAddressBeanSparseArray);
    }


    @Click({R.id.add_addr_rl, R.id.app_common_header_left_icon_iv,
            R.id.addr_city_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_addr_rl:
                locationUtil.startLocation();
                break;
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.addr_city_tv:
                ChooseProvinceActivity_.intent(SetAddrActivity.this).startForResult(Constant.ADDR_SET_REQUEST_CODE);
                break;
            default:
                break;
        }
    }


    //获得定位
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation == null) {
            TUtil.showShort(this, R.string.fail_location);
            return;
        }

        if (bdLocation.hasAddr()) {
            if (needLocation) {
                String cityName = bdLocation.getCity();
                setLocationCity(cityName);
            } else {
                setLocationResult(bdLocation);
            }
        }
    }


    //通过定位实现跳转
    void setLocationResult(BDLocation bdLocation) {
        JsAddrBean addrBean = new JsAddrBean();
        addrBean.setPreAddr(bdLocation.getAddrStr());
        addrBean.setSubAddr("");
        addrBean.setDetailAddr("");
        addrBean.setLonPoint(bdLocation.getLongitude());
        addrBean.setLatPoint(bdLocation.getLatitude());
        String cityName = bdLocation.getCity();
        addrBean.setCity(cityName);
        long cityId = getCityId(cityName);
        //Jpush
        Set<String> tags = new HashSet<String>();
        tags.add(cityId + "");
        if (appPref.userId().get() > 0) {
            JPushInterface.setAliasAndTags(this, null, tags, mAliasCallback);
        }

        addrBean.setCityId(cityId);
        Gson gson = new Gson();
        appPref.edit().userAddress().put(bdLocation.getAddrStr()).apply();
        appPref.edit().city().put(cityName).apply();
        appPref.edit().cityId().put(cityId).apply();
        appPref.edit().latPoint().put(bdLocation.getLongitude() + "").apply();
        appPref.edit().lonPoint().put(bdLocation.getLatitude() + "").apply();

        String userInfo = gson.toJson(addrBean);
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.VALUE, userInfo);
        intent.putExtras(bundle);
        setResult(Constant.ADDR_SET_RESULT_CODE, intent);
        finish();
    }

    //设置定位当前城市信息
    void setLocationCity(String cityName) {
        if (StringUtils.isBlank(cityName)) {
            needLocation = true;
            locationUtil.startLocation();
        } else {
            needLocation = false;
            city_tv.setText(cityName);
        }
    }


    @UiThread
    //poi 检索监听
    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        //取消对话框
        dissLoadingDialog();
        adapter.clear();
        poiArray = new SparseArray<UserAddressBean>();
        if (poiResult == null || poiResult.error != SearchResult.ERRORNO.NO_ERROR) {
            setPoiSearchHint();
            return;
        }
        UserAddressBean userAddressBean;
        int m = 0;
        for (PoiInfo info : poiResult.getAllPoi()) {
            userAddressBean = new UserAddressBean();
            String detailAddr = info.name;
            userAddressBean.setDetailAddr(detailAddr);
            String preAddr = info.address;
            userAddressBean.setPreAddr(preAddr);
            String subAddr = "";
            userAddressBean.setSubAddr(subAddr);
            long cityId = getCityId(info.city);
            userAddressBean.setCityId(cityId);
            LatLng latLng = info.location;
            if (latLng != null) {
                double latPoint = latLng.latitude;
                userAddressBean.setLatPoint(latPoint);
                double lonPoint = latLng.longitude;
                userAddressBean.setLonPoint(lonPoint);
                LUtil.i(LOG_TAG, "____经纬度_" + latPoint);
            }
            poiArray.put(m, userAddressBean);
            m++;
            LUtil.i(LOG_TAG, "____地址___city_" + info.city + "___address___" + info.address + "name" + info.name);
        }

        loadMoreData(poiArray);
        setPoiSearchHint();

    }


    //获得城市Id
    long getCityId(String cityName) {
        getHelper();
        cityDao = new CityDao();
        cityDao.setHelper(helper);
        list = cityDao.findAll();
        for (City city : list) {
            if (cityName.equals(city.getCityName())) {
                LUtil.i(LOG_TAG, "_______获取城市ID_" + city.getCityId());
                return city.getCityId();
            }
        }
        return 0;
    }


    //获得城市Id
    String getCityName(long cityId) {
        getHelper();
        cityDao = new CityDao();
        cityDao.setHelper(helper);
        list = cityDao.findAll();
        for (City city : list) {
            if (cityId == city.getCityId()) {
                LUtil.i(LOG_TAG, "_______获取城市名_" + city.getCityName());
                return city.getCityName();
            }
        }
        return "";
    }


    //slite 实例
    void getHelper() {
        if (helper == null) {
            helper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
        }
    }


    //设置POI搜索结果提示title
    @UiThread
    void setPoiSearchHint() {
        String hint = getResources().getString(R.string.poi_search_hint, "”" + materialEditText.getText().toString() + "”");
        SpannableString spannableString = new SpannableString(hint);
        spannableString.setSpan(new ForegroundColorSpan(Color.RED)
                , 1, materialEditText.getText().toString().length() + 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        history_addr_or_searchResult_tv.setText(spannableString);
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    //通过poi 设置地址后跳转
    void setPoiAddrResult(int position) {
        UserAddressBean addressBean = adapter.getArrys().get(position);
        Gson gson = new Gson();
        JsAddrBean addrBean = new JsAddrBean();
        addrBean.setDetailAddr(addressBean.getDetailAddr());
        addrBean.setLatPoint(addressBean.getLatPoint());
        addrBean.setSubAddr(addressBean.getSubAddr());
        long cityId = addressBean.getCityId();
        //Jpush
        Set<String> tags = new HashSet<String>();
        tags.add(cityId + "");
        if (appPref.userId().get() > 0) {
            JPushInterface.setAliasAndTags(this, null, tags, mAliasCallback);
        }

        addrBean.setCityId(cityId);
        String cityName = getCityName(cityId);
        LUtil.i(LOG_TAG, "_____setPoiAddrResult_____" + cityName + "______cityID______" + cityId);
        addrBean.setCity(cityName);
        addrBean.setLonPoint(addressBean.getLonPoint());
        addrBean.setPreAddr(addressBean.getPreAddr());

        //存储一些地址信息
        String detail = addressBean.getPreAddr() + addressBean.getSubAddr() + addressBean.getDetailAddr();
        appPref.edit().userAddress().put(detail).apply();
        appPref.edit().city().put(cityName).apply();
        appPref.edit().cityId().put(cityId).apply();
        appPref.edit().latPoint().put(addressBean.getLatPoint() + "").apply();
        appPref.edit().lonPoint().put(addressBean.getLonPoint() + "").apply();

        String userInfo = gson.toJson(addrBean);
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.VALUE, userInfo);
        intent.putExtras(bundle);
        setResult(Constant.ADDR_SET_RESULT_CODE, intent);
        finish();
    }


    //推送设置标签回调
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LUtil.i(LOG_TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LUtil.i(LOG_TAG, logs);
                    setTags(tags);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LUtil.i(LOG_TAG, logs);
            }
        }
    };

    //设置标签
    @Background(delay = 60000)
    void setTags(Set<String> tags) {
        JPushInterface.setAliasAndTags(this, null, tags, mAliasCallback);
    }


    @Override
    public void onRecyclerItemClicked(int position) {
        setPoiAddrResult(position);
        LUtil.i(LOG_TAG, "_______位置_______" + position);

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        locationUtil.stopLocation();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (helper != null) {
            OpenHelperManager.releaseHelper();
            helper = null;
        }
        if (poiSearchUtil != null) {
            poiSearchUtil.destory();
        }
    }
}